from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import os

app = Flask(__name__)
CORS(app)  # Enable CORS

# 修改数据文件路径
DATA_FILE = "f:/game/pvp/data/player_data.json"

def load_players():
    if not os.path.exists(DATA_FILE):
        return {}
    with open(DATA_FILE, 'r') as f:
        return json.load(f)

def save_players(players):
    with open(DATA_FILE, 'w') as f:
        json.dump(players, f)

@app.route('/register', methods=['POST'])
def register():
    if not request.is_json:
        return jsonify({"success": False, "message": "Request must be JSON format"}), 400
    
    try:
        data = request.get_json()
        if not data:
            return jsonify({"success": False, "message": "Request body cannot be empty"}), 400
            
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({"success": False, "message": "Username and password cannot be empty"}), 400
            
        players = load_players()
        
        if username in players:
            return jsonify({"success": False, "message": "Username already exists"})
        
        players[username] = {
            "password": password,
            "current_hp": 100,
            "inventory": [],
            "eggs": []
        }
        
        save_players(players)
        return jsonify({"success": True, "message": "Registration successful"})
        
    except Exception as e:
        return jsonify({"success": False, "message": "Internal server error"}), 500

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    players = load_players()
    
    if username not in players or players[username]['password'] != password:
        return jsonify({"success": False, "message": "Invalid username or password"})
    
    # Return player's game data
    return jsonify({
        "success": True, 
        "message": "Login successful",
        "game_data": {
            "current_hp": players[username].get('current_hp', 100),
            "inventory": players[username].get('inventory', []),
            "eggs": players[username].get('eggs', [])  # 改用eggs字段
        }
    })

@app.route('/save_game', methods=['POST'])
def save_game():
    data = request.get_json()
    username = data.get('username')
    game_data = data.get('game_data')
    
    players = load_players()
    if username in players:
        players[username].update({
            'current_hp': game_data.get('current_hp'),
            'inventory': game_data.get('inventory', []),
            'eggs': game_data.get('eggs', [])
        })
        save_players(players)
        return jsonify({"success": True, "message": "Save successful"})
    return jsonify({"success": False, "message": "User not found"})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)